/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.sql.Connection;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import javax.servlet.http.HttpSession;
import model.pojo.*;
import model.dao.*;
import model.util.MySQLProviders;
/**
 *
 * @author VuTienIT
 */
public class ThongTinKH extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        request.removeAttribute("Error_MatKhauRe");
        request.removeAttribute("Error_NN");
        request.removeAttribute("Error_DC");
        request.removeAttribute("Error_DTNN");
        request.removeAttribute("Error_KV");
        request.removeAttribute("Error_Q");
        String page = request.getParameter("Page");
        String m = request.getParameter("m");
        String action = request.getParameter("Action"); 
        //Lấy giỏ hàng
        ArrayList<PhieuPOJO> gioHang = null;
        if(session.getAttribute("GioHang")==null)
        {
            gioHang = new ArrayList<PhieuPOJO>();
            session.setAttribute("GioHang", gioHang);
        }
        else
        {
            gioHang = (ArrayList<PhieuPOJO>)session.getAttribute("GioHang");
        }
        //Session đăng nhập
        KhachHangPOJO ssDangNhap = null;
        if(session.getAttribute("KhachHang")==null)
        {
            ssDangNhap = new KhachHangPOJO();
            session.setAttribute("KhachHang", ssDangNhap);
        }
        else
        {
            ssDangNhap = (KhachHangPOJO)session.getAttribute("KhachHang");
        }      
        
        if(page==null)
        {
            if(ssDangNhap.getTenTruyCap()!=null)
            {
                request.getRequestDispatcher("/ThongTinKH.jsp").forward(request, response);
            }
            else
            {
                response.sendRedirect("home?Page=View");
            }
        }
        if(page!=null)
        {
            ArrayList<DanhMucPOJO> danhMucs = DanhMucDAO.getDanhSach();
            request.setAttribute("DanhMucS", danhMucs);
            ArrayList<PhieuPOJO> dsKMt = PhieuDAO.getDanhSachKMHnay3();
            request.setAttribute("PhieuKM", dsKMt);
            if(ssDangNhap.getTenTruyCap()!=null)
            {
                
                //Cài đặt tài khoản
                if(page.equals("info"))
                {
                    String matkhau = request.getParameter("matkhau");
                    String golaiMK = request.getParameter("golaimatkhau");
                    String dienthoai = request.getParameter("sodienthoai");
                    int thanhpho = 0;
                    if(request.getParameter("thanhpho")!=null){
                        thanhpho = Integer.parseInt(request.getParameter("thanhpho"));
                    }  
                    if(matkhau!=null && !matkhau.equals(golaiMK))
                    {
                        request.setAttribute("Error_MatKhauRe", "Nhập lại mật khẩu không đúng");
                        request.getRequestDispatcher("/ThongTinKH.jsp").forward(request, response);
                    }
                    if(matkhau=="")
                    {
                        matkhau = ssDangNhap.getMatKhau();
                    }
                    if(action!=null && action.equals("Update"))
                    {
                        KhachHangPOJO kh = new KhachHangPOJO();
                        kh.setTenTruyCap(ssDangNhap.getTenTruyCap());
                        kh.setMaKhuVuc(thanhpho);
                        kh.setSoDienThoai(dienthoai);
                        kh.setMatKhau(matkhau);
                        int flag = KhachHangDAO.CapNhatTTKhachHang(kh);
                        if(flag==1)
                        {
                            request.setAttribute("ThongBao", "Cập nhật thông tin thành công");
                        }
                        ssDangNhap = KhachHangDAO.DangNhap(ssDangNhap.getTenTruyCap(),ssDangNhap.getMatKhau());
                        session.setAttribute("KhachHang", ssDangNhap);
                        request.getRequestDispatcher("/ThongTinKH.jsp").forward(request, response);
                    }
                    request.getRequestDispatcher("/ThongTinKH.jsp").forward(request, response);
                }
                
                //Thông tin giao hàng
                if(page.equals("recp"))
                {
                    ArrayList<KhuVucPOJO> dsKV = new ArrayList<KhuVucPOJO>();
                    if(ssDangNhap.getMaKhuVuc()==-1)
                    {
                        dsKV = KhuVucDAO.getDanhSach();
                    }
                    else if(ssDangNhap.getMaKhuVuc()!=-1)
                    {
                        dsKV = KhuVucDAO.getDanhSachLoaiTru(ssDangNhap.getMaKhuVuc());
                    }
                    request.setAttribute("KhuVucS", dsKV);
                    if(ssDangNhap.getMaQuan()!=-1)
                    {
                        QuanPOJO q1 = QuanDAO.getQuan(ssDangNhap.getMaQuan());
                        request.setAttribute("GetQuan", q1);
                    }
                    if(ssDangNhap.getMaKhuVuc()!=-1)
                    {
                        KhuVucPOJO q1 = KhuVucDAO.getKhuVuc(ssDangNhap.getMaKhuVuc());
                        request.setAttribute("GetKhuVuc", q1);
                    }
                    if(action!=null && action.equals("ud"))
                    {
                        String nguoinhan = request.getParameter("nguoinhan");
                        String diachi = request.getParameter("diachi");
                        String dtnguoinhan = request.getParameter("dienthoai");
                        int thanhpho = ssDangNhap.getMaKhuVuc();
                        int maQuan = -1;
                        if(nguoinhan=="" || diachi=="" || dtnguoinhan==""
                                || request.getParameter("thanhpho").equals("999999") || request.getParameter("quan").equals("999999"))
                        {
                            if(nguoinhan=="")
                            {
                                request.setAttribute("Error_NN", "Thiếu thông tin");
                            }
                            if(diachi=="")
                            {
                                request.setAttribute("Error_DC", "Thiếu thông tin");
                            }
                            if(dtnguoinhan=="")
                            {
                                request.setAttribute("Error_DTNN", "Thiếu thông tin");
                            }
                            if(request.getParameter("thanhpho").equals("999999"))
                            {
                                request.setAttribute("Error_KV", "Chưa chọn thành phố");
                            }  
                            if(request.getParameter("quan").equals("999999"))
                            {
                                request.setAttribute("Error_Q", "Chưa chọn Quận - Huyện");
                            }
                            request.getRequestDispatcher("/ThongTinNN.jsp").forward(request, response);
                        }
                        else
                        {
                            if(!request.getParameter("thanhpho").equals("999999"))
                            {
                                thanhpho = Integer.parseInt(request.getParameter("thanhpho"));
                            }  
                            if(!request.getParameter("quan").equals("999999"))
                            {
                                maQuan = Integer.parseInt(request.getParameter("quan"));
                            }
                        
                            KhachHangPOJO kh1 = new KhachHangPOJO();
                            kh1.setTenTruyCap(ssDangNhap.getTenTruyCap());
                            kh1.setNguoiNhan(nguoinhan);
                            kh1.setDiaChi(diachi);
                            kh1.setSoDTNguoiNhan(dtnguoinhan);
                            kh1.setMaKhuVuc(thanhpho);
                            kh1.setMaQuan(maQuan);
                            int flag = KhachHangDAO.CapNhatDiaChiKhachHang(kh1);   
                            
                            ssDangNhap = KhachHangDAO.DangNhap(ssDangNhap.getTenTruyCap(),ssDangNhap.getMatKhau());
                            session.setAttribute("KhachHang", ssDangNhap);
                            if(ssDangNhap.getMaQuan()!=-1)
                            {
                                QuanPOJO q1 = QuanDAO.getQuan(ssDangNhap.getMaQuan());
                                request.setAttribute("GetQuan", q1);
                            }
                            if(ssDangNhap.getMaKhuVuc()!=-1)
                            {
                                KhuVucPOJO q1 = KhuVucDAO.getKhuVuc(ssDangNhap.getMaKhuVuc());
                                request.setAttribute("GetKhuVuc", q1);
                            }
                            if(ssDangNhap.getMaKhuVuc()==-1)
                            {
                                dsKV = KhuVucDAO.getDanhSach();
                            }
                            else if(ssDangNhap.getMaKhuVuc()!=-1)
                            {
                                dsKV = KhuVucDAO.getDanhSachLoaiTru(ssDangNhap.getMaKhuVuc());
                            }
                            request.setAttribute("KhuVucS", dsKV);
                            if(m!=null && m.equals("ck"))
                            {
                                String chuthich = request.getParameter("chuthich");
                                int ptttoan = 3;
                                int chuyenhang = 1;
                                if(request.getParameter("rbnPhuongThuc")!=null){
                                    ptttoan = Integer.parseInt(request.getParameter("rbnPhuongThuc"));
                                }
                                if(request.getParameter("rbnChuyenhang")!=null){
                                    chuyenhang = Integer.parseInt(request.getParameter("rbnChuyenhang"));
                                }
                                double s = 0;
                                for(int i=0;i<gioHang.size();i++)
                                {
                                    PhieuPOJO giay = gioHang.get(i);
                                    double tongtien = giay.getGiaBan()*giay.getSoLuongQuyDinh();
                                    gioHang.get(i).setThanhTienGioHang(tongtien);
                                    s = s + tongtien;
                                }
                                MySQLProviders helper  = new MySQLProviders();
                                helper.open();
                                Connection con = helper.getConnection();
                                con.setAutoCommit(false);
                                try {
                                    DonDatHangPOJO hd = new DonDatHangPOJO();
                                    hd.setTenDangNhap(ssDangNhap.getTenTruyCap());
                                    hd.setMaTinhTrang(1);
                                    hd.setTongTien(s);
                                    hd.setChuThich(chuthich);
                                    hd.setHinhThucThanhToan(ptttoan);
                                    hd.setPhuongThucChuyenHang(chuyenhang);
                                    hd.setNguoiNhan(nguoinhan);
                                    hd.setDiaChi(diachi);
                                    hd.setDienThoai(dtnguoinhan);
                                    hd.setMaKhuVuc(thanhpho);
                                    hd.setMaQuan(maQuan);
                                    int MaHD = DonDatHangDAO.ThemHoaDon2(hd,con);
                                    KhachHangDAO.CapNhatSoDuTK(hd.getTenDangNhap(), s, "-", helper);
                                    //Lưu các chi tiết đơn đặt hàng
                                    for(int i=0;i<gioHang.size();i++)
                                    {
                                        PhieuPOJO giay = gioHang.get(i);
                                        int soThuTu = i + 1;
                                        CTDHPOJO cthd = new CTDHPOJO();
                                        cthd.setMaDonDatHang(MaHD);
                                        cthd.setSoThuTu(soThuTu);
                                        cthd.setMaPhieu(giay.getMaPhieu());
                                        cthd.setSoLuong(giay.getSoLuongQuyDinh());
                                        cthd.setGiaBan(giay.getGiaBan());
                                        cthd.setThanhTien(giay.getThanhTienGioHang());
                                        boolean flag1 = false;
                                        flag1 = PhieuDAO.KiemTraSoLuongDatHang(cthd.getMaPhieu(), cthd.getSoLuong(),helper);
                                        if(!flag1)
                                        {
                                            System.out.println("Số lượng không phù hợp !");
                                            con.rollback();
                                            request.setAttribute("Error", "Số lượng không phù hợp !");
                                            request.getRequestDispatcher("error.jsp").forward(request, response);
                                            return;
                                        }
                                        CTDonDatHangDAO.ThemCTHD(cthd,helper);
                                    }
                                    con.commit();
                                    request.setAttribute("ThongBaoDH", "Đặt hàng thành công !");
                                    String url = String.format("GioHang?Page=DatHang&MaHoaDon=%d",MaHD);
                                    //response.sendRedirect(url);
                                    request.getRequestDispatcher(url).forward(request, response);
                                } catch (SQLException e) {
                                    con.rollback();
                                }
                                helper.close();
                                request.getRequestDispatcher("/ThongTinGiaoHang.jsp").forward(request, response);
                            }
                            else if(m==null)
                            {
                                if(flag==1)
                                {
                                    request.setAttribute("ThongBao", "Cập nhật thông tin thành công");
                                }
                                else
                                {
                                    request.setAttribute("ThongBao", "Có lỗi xảy ra. Cập nhật thông tin không thành công");
                                }
                                request.getRequestDispatcher("/ThongTinNN.jsp").forward(request, response);
                            }
                        }
                    }
                    if(m!=null && m.equals("ck"))
                    {
                        request.getRequestDispatcher("/ThongTinGiaoHang.jsp").forward(request, response);
                    }
                    else if(m==null)
                    {
                        request.getRequestDispatcher("/ThongTinNN.jsp").forward(request, response);
                    }
                }
                
                //Lịch sử mua hàng
                if(page.equals("History"))
                {
                    ArrayList<DonDatHangPOJO> dsHD = DonDatHangDAO.getDonDatHang2(ssDangNhap.getTenTruyCap());
                    request.setAttribute("DonDatHangS", dsHD);
                    if(action!=null && action.equals("Huy"))
                    {
                        int MaDonDatHang = Integer.parseInt(request.getParameter("MaDonDatHang"));
                        DonDatHangPOJO dh = new DonDatHangPOJO();
                        dh = DonDatHangDAO.getDonDatHang(MaDonDatHang);
                        ArrayList<CTDHPOJO> ctdh = new ArrayList<CTDHPOJO>();
                        ctdh = CTDonDatHangDAO.getDanhSach(MaDonDatHang);
                        
                        if(dh.getMaTinhTrang()!=2)
                        {
                            MySQLProviders helper = new MySQLProviders();
                            helper.open();
                            Connection con = helper.getConnection();
                            con.setAutoCommit(false);
                            try
                            {
                                DonDatHangDAO.HuyHoaDon(dh, con);
                                for (int i=0;i<ctdh.size();i++)
                                {
                                    PhieuPOJO p = new PhieuPOJO();
                                    p.setSoLuongMua(ctdh.get(i).getSoLuong());
                                    PhieuDAO.CapNhatSoLuongHuy(p,ctdh.get(i).getMaPhieu(), helper);
                                    KhachHangDAO.CapNhatSoDuTK(ssDangNhap.getTenTruyCap(), ctdh.get(i).getThanhTien() , "+", helper);
                                }
                                
                                System.out.printf("Huy don hang thanh cong");
                                con.commit();
                            }
                            catch(SQLException e)
                            {
                                con.rollback();
                            }
                            finally
                            {
                                helper.close();
                            }
                        }
                        dsHD = DonDatHangDAO.getDonDatHang2(ssDangNhap.getTenTruyCap());
                        request.setAttribute("DonDatHangS", dsHD);
                        request.getRequestDispatcher("/QuanLyDonHang.jsp").forward(request, response);
                    }
                    request.getRequestDispatcher("/QuanLyDonHang.jsp").forward(request, response);
                }
                if(page.equals("Detail"))
                {
                    if(request.getParameter("MaDonDatHang")!=null)
                    {
                        int maHD = Integer.parseInt(request.getParameter("MaDonDatHang"));
                        ArrayList<CTDHPOJO> dsHD = CTDonDatHangDAO.getDanhSach(maHD);
                        request.setAttribute("CTDonDatHangS", dsHD);
                        request.getRequestDispatcher("/ChiTietDonHang.jsp").forward(request, response);
                    }
                    else
                    {
                        response.sendRedirect("ThongTinKH?Page=History");
                    }
                }
                if(page.equals("ref"))
                {
                    ArrayList<NhatKyMoiBanPOJO> dsNK = NhatKyMoiBanDAO.LoadDanhSach(ssDangNhap.getTenTruyCap());
                    request.setAttribute("NhatKyMoiBanS", dsNK);
                    request.getRequestDispatcher("/NhatKyMoiBan.jsp").forward(request, response);
                }
            }
            else
            {
                response.sendRedirect("home?Page=View");
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ThongTinKH.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ThongTinKH.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
